<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\controller;
use think\facade\Db;
use app\wework\controller\Base;
use Ramsey\Uuid\Uuid;
use think\facade\Session;
use app\wework\model\Basemodel;
use app\wework\model\MediaModel;
use OSS\OssClient;
use Qcloud\Cos\Client;
use OSS\Core\OssException;
use think\facade\Filesystem;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;


/**
* 媒体类
**/
class Media extends Base
{
    /**
   * 获取素材分类分组
   * @return 
   */
   public function group(){
      $gsType = $this->req->param('gs_type',1);
      $data = MediaModel::group($gsType);
      return success('素材分类分组',$data);
   }
    /**
   * 添加|修改 素材分类分组
   * @param groupid 分组id, 不填则为添加
   * @param name 分组名
   * @return 
   */
   public function groupAdd(){
      $wid = Session::get('wid');
      $title = $this->req->post('title');
      $gsType = $this->req->post('gs_type');
      if(!$title) return error('请输入名称');
      if(!$gsType) return error('请输入类型');
      $res = MediaModel::groupAdd($title,$gsType);
      if($res!='ok') return error($res);
      return success('操作成功');
   }
   /**
   * 删除素材分类分组
   * @param groupid 分组id
   * @return 
   */
   public function groupUpdate(){
      $wid = Session::get('wid');
      $update = $this->req->post('update',[]);
      $delete = $this->req->post('delete',[]);
      if(!$update && !$delete) return error('参数不能全部为空');
      $res = MediaModel::groupUpdate($update,$delete);
      if($res != 'ok') return error($res);
      return success('操作成功');
   }

   public function deletes(){
      $id = $this->req->param("id");
      $url = $this->req->domain();
      $res = MediaModel::deletes($id,$url);

      return success('操作成功');
   }

    /**
     * 图片库列表
     * @return \think\Response
     */
    public function imgIndex()
    {   
        $page = $this->req->param('page',1);
        $size = $this->req->param('size',10); 
        $groupId = $this->req->param('group_id',0); 
        $gsType = $this->req->param('gs_type',1); 
        $name = $this->req->param('name'); 
        $res = MediaModel::imgList($page,$size,$groupId,$gsType,$name);
        return success('图片库列表',$res);
    }
    /**
     * 更新素材
     * @return \think\Response
     */
    public function imgUpdate()
    {   
        $wid = Session::get('wid'); 
        $id = $this->req->post('id');
        if(!$id) return error('请选择素材');
        $groupId = $this->req->post('group_id');
        $name = $this->req->post('name');
        if(!$groupId && !$name) return error('分组id和名称不能同时为空');
        $data = [];
        if($groupId) $data['groupid'] = $groupId;
        if($name) $data['name'] = $name;
        $res = MediaModel::imgUpdate($id,$data);
        if($res == 0) return error('无修改');
        return success('更新成功');
    }

   /**
     * oss数据
     * @return \think\Response
     */
    public function index()
    {   
        
        $res = MediaModel::storageInfo($this->wid);
        return success('云存储配置',$res);
    }

    /**
     * 云存储服务器配置保存
     * @return \think\Response
     */
    public function save()
    {   
        $data = [];
        $data = $this->req->post();
        if($data['type'] == 2 && !$data['oss_id'] && !$data['oss_secret'] && !$data['oss_endpoint']) return error('参数错误');
        if($data['type'] == 3 && !$data['cos_secretId'] && !$data['cos_secretKey'] && !$data['cos_bucket'] && !$data['cos_endpoint']) return error('参数错误');
        if($data['type'] == 4 && !$data['kodo_key'] && !$data['kodo_secret'] && !$data['kodo_domain'] && !$data['kodo_bucket']) return error('参数错误');
        $res = MediaModel::storageUpdate($this->wid,$data);
        if($res == 0) return error('无修改');
        return success('更新成功');
    }

    public function uploadTxt(){
          $files = request()->file('file');
          if(!$files) return error('未检测到上传资源');
          $imgTruePath = $files->getPathname(); //获取临时地址
          $minType = $files->getOriginalName(); //获取后缀
          $fileName = $files->getOriginalName(); //获取上传名
          $time = date('Y-m-d');
          $url = $this->req->domain()."/".Filesystem::disk('public')->putFileAs("", $files,$fileName);

          return success('上传成功',["url"=>$url,"file_name"=>$fileName]);
    }

    //上传图片
    public function uploadFile(){
        $wid = Session::get("wid");
        $user = Db::table("kt_base_user")->where(["id"=>$wid])->find();
        $files = request()->file('file');
        if(!$files) return error('未检测到上传资源');
        $storage = MediaModel::storageInfo($this->wid);
        $type = 1;
        $groupid = request()->param('groupid',0);
        $file_name = $files->getOriginalName();
        $ext = $files->extension(); //获取后缀
        $mediatype = in_array($ext, ['jpg','png','gif']) ? 1 : (in_array($ext, ['mp4','avi','rmvb','rm','mpg','mpeg','wmv','mkv','flv']) ? 2 : 0);
        if(!$groupid && $mediatype) $groupid = MediaModel::inisetImg($mediatype);
        if(in_array($ext,["xlsx"]))$type = 1;
          switch ($type) {
            case 1:
                $imgTruePath = $files->getPathname(); //获取临时地址
                $minType = $files->getOriginalName(); //获取后缀
                $fileName = $files->getOriginalName(); //获取上传名
                $time = date('Y-m-d');
                $url = $this->req->domain()."/".Filesystem::disk('public')->putFile( 'upload/wework/'.$time, $files, 'md5');
                if($groupid){
                     $data = [
                        'wid' => $wid,
                        'name' => $fileName,
                        'oss_type' => 1,
                        'groupid' => $groupid,
                        'gs_type' => $mediatype,
                        'url'=> $url,
                        'create_time'=> date("Y-m-d H:i:s"),
                        'update_time'=> date("Y-m-d H:i:s"),
                    ];
                    MediaModel::imgSave($data);
                }
                break;
            case 2:
                $url = $this->uploadOss($storage,$files,$groupid);
                break;
            case 3:
                $url = $this->uploadCos($storage,$files,$groupid);
                break;
            case 4:
                $url = $this->uploadKodo($storage,$files,$groupid);
                break;
          }
        
        return success('上传成功',["url"=>$url,"file_name"=>$file_name]);
    }

    /**
     * 上传到Oss
     * @return \think\Response
     */
    public function uploadOss($storage,$file,$groupid)
    {
        $wid = Session::get("wid");
        $user = Db::table("kt_base_user")->where(["id"=>$wid])->find();
      $accessKeyId      = $storage['oss_id'];
    $accessKeySecret  = $storage['oss_secret'];
    $endpoint  = $storage['oss_endpoint'];
    $bucket = "wework";
        $bucket = $storage['oss_bucket'];
    try {
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        // 设置Socket层传输数据的超时时间
        $ossClient->setTimeout(3600);
        // 设置建立连接的超时时间，单位秒，默认10秒。
        $ossClient->setConnectTimeout(10);
        $bucketExist = $ossClient->doesBucketExist($bucket);  //判断bucket是否存在
      $imgTruePath = $file->getPathname(); //获取临时地址
      $minType = $file->extension(); //获取后缀
      $fileName = $file->getOriginalName();
      $filePath = 'wework/'.$wid.'/'.uniqid('wework_').'.'.$minType;
        $uploadOssRes = $ossClient->uploadFile($bucket, $filePath, $imgTruePath);
        $url = $uploadOssRes['info']['url'];
            $mediatype = in_array($ext, ['jpg','png','gif']) ? 1 : (in_array($ext, ['mp4','avi','rmvb','rm','mpg','mpeg','wmv','mkv','flv']) ? 2 : 0);
          if($groupid){
                 $data = [
                    'wid' => $wid,
                    'name' => $fileName,
                    'groupid' => $groupid,
                    'gs_type' => $mediatype,
                    'oss_type' => 2,
                    'url'=> $url,
                    'create_time'=> date("Y-m-d H:i:s"),
                    'update_time'=> date("Y-m-d H:i:s"),
                ];
                MediaModel::imgSave($data);
            }
        return $url;
    } catch (OssException $e) {
        print $e->getDetails();  //调试时,打开,输出错误信息
        return '上传失败';
    }

    }

    /**
    * 上传到Cos
    * @return \think\Response
    */
    public function uploadCos($storage,$file,$groupid)
    {
        $wid = Session::get("wid");
        $user = Db::table("kt_base_user")->where(["id"=>$wid])->find();
        $secretId = $storage['cos_secretId']; 
        $secretKey = $storage['cos_secretKey']; 
        $endpoint = $storage['cos_endpoint'];
        $bucket = $storage['cos_bucket'];
        $regionArr =  explode('.', $endpoint);
        $region = $regionArr[2]; 
        $cosClient = new Client(
            array(
                'region' => $region,
                'schema' => 'https', //协议头部，默认为http
                'credentials'=> array(
                    'secretId'  => $secretId ,
                    'secretKey' => $secretKey)));
        $imgTruePath = $file->getPathname(); //获取临时地址
        $ext = $file->extension(); //获取后缀
        $minType = $file->getMime(); //获取文件类型
        $fileName = $file->getOriginalName();
        $filePath = 'wework/'.$wid.'/'.uniqid('wework_').'.'.$ext;
        try {
            $result = $cosClient->putObject(
                array(
                    'Bucket' => $bucket,
                    'Key' => $filePath,
                    'Body' => fopen($imgTruePath, 'rb')
                )
            );
            $url = "https://".$result['Location'];
            if(in_array($ext, ['jpg','png','gif'])){
                $mediatype = in_array($ext, ['jpg','png','gif']) ? 1 : (in_array($ext, ['mp4','avi','rmvb','rm','mpg','mpeg','wmv','mkv','flv']) ? 2 : 0);
                $data = [
                    'wid' => $wid,
                    'name' => $fileName,
                    'groupid' => $groupid,
                    'gs_type' => $mediatype,
                    'oss_type' => 3,
                    'url'=> $url,
                    'create_time'=> date("Y-m-d H:i:s"),
                    'update_time'=> date("Y-m-d H:i:s"),
                ];
                MediaModel::imgSave($data);
            }
            
            return $url;
        }catch (\Exception $e) {  
            return 'error';
        }
    }

    /**
    * 上传到kodo 七牛云
    * @return \think\Response
    */
    public function uploadKodo($storage,$file,$groupid)
    {
        $wid = Session::get("wid");
        $user = Db::table("kt_base_user")->where(["id"=>$wid])->find();
        $accessKey = $storage['kodo_key'];
        $secretKey = $storage['kodo_secret'];
        $bucket = $storage['kodo_bucket'];
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        $imgTruePath = $file->getPathname(); //获取临时地址
        $ext = $file->extension(); //获取后缀
        $minType = $file->getMime(); //获取文件类型
        $fileName = $file->getOriginalName();
        $filePath = 'wework/'.$wid.'/'.uniqid('wework_').'.'.$ext;
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $filePath, $imgTruePath);
        if ($err !== null) {
            return 'error';
        } else {
            $url = 'http://' . $storage['kodo_domain'] . '/' . $ret['key'];
            if(in_array($ext, ['jpg','png','gif'])){
                $mediatype = in_array($ext, ['jpg','png','gif']) ? 1 : (in_array($ext, ['mp4','avi','rmvb','rm','mpg','mpeg','wmv','mkv','flv']) ? 2 : 0);
                $data = [
                    'wid' => $wid,
                    'name' => $fileName,
                    'groupid' => $groupid,
                    'gs_type' => $mediatype,
                    'oss_type' => 4,
                    'url'=> $url,
                    'create_time'=> date("Y-m-d H:i:s"),
                    'update_time'=> date("Y-m-d H:i:s"),
                ];
                MediaModel::imgSave($data);
            }
            
            return $url;
        }
    }
    
}